package org.ztest.redis;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class TestJedis
{
	private final int TEST_NUM = 100000;
	private ExecutorService exe = Executors.newFixedThreadPool(50);
	
	public void test()
	{
		useMSet();
		
		useSingleSet();
	}
	
	public void useMSet()
	{
		JedisPoolConfig cfg = new JedisPoolConfig();
		cfg.setMaxTotal(50);
		@SuppressWarnings("resource")
        JedisPool jedisPool = new JedisPool(cfg, "192.168.19.134", 6379, 10000);
		
		String[] sets = new String[TEST_NUM * 2];
		long start = System.currentTimeMillis();
		int i = 0;
		while (i < TEST_NUM)
		{
			sets[2 * i] = String.valueOf(i);
			sets[2 * i + 1] = String.valueOf(i);
			i++;
		}
		
		try (Jedis conn = jedisPool.getResource())
		{
			conn.mset(sets);
		}
		System.out.println((System.currentTimeMillis() - start));
	}
	
	public void useSingleSet()
	{
		JedisPoolConfig cfg = new JedisPoolConfig();
		cfg.setMaxTotal(50);
		@SuppressWarnings("resource")
        JedisPool jedisPool = new JedisPool(cfg, "192.168.19.134", 6379, 10000);
		
		long start = System.currentTimeMillis();
		int i = 0;
		AtomicInteger ai = new AtomicInteger(0);
		while (i++ < TEST_NUM)
		{
			final int val = i;
			exe.submit(() -> {
				try (Jedis conn = jedisPool.getResource())
				{
					conn.set(String.valueOf(val), String.valueOf(val));
				}
				if (ai.incrementAndGet() == TEST_NUM)
				{
					System.out.println((System.currentTimeMillis() - start));
				}
			});
		}
	}
}
